//注册页面
import React, { useEffect, useRef, useState } from 'react';
import { Button, Image, Input, Text, View } from '@tarojs/components';
import TitleBar from '@/src/components/titleBar';
import Taro, { useDidShow } from '@tarojs/taro';
import CommonPopup from '@/src/components/commonPopup';
import LoadingSpinner from '@/src/components/loadingSpinner';
import './index.less';
import TitleBarLeft from '@/src/components/titleBarLeft';
import {
  oauthTokenFun,
  sendCodeFun,
  updateBasicInfoFun,
  userInfoFun,
} from '@/src/common/method/loginFun';
import store from '@/src/store';
import { showToast, StatusToast } from '@/src/components/statusToast';
import { loginErrorInfo, netWorkErrorInfo } from '@/src/utils/constants';
import { getNetWorkStatus } from '@/src/common/util/util';
import { updateInfoFun } from '@/src/common/method/userInfoFun';
import {
  feature,
  getRandomCombination,
  identity,
  sence,
} from '@/src/utils/commonFun';
import { safeBack } from '@/src/common/method/commonFun';
const Register = () => {
  const [captcha, setCaptcha] = useState('');
  const [countdown, setCountdown] = useState(0);
  const [isSending, setIsSending] = useState(false);
  const timerRef = useRef<any>(null);
  const [selected, setSelected] = useState<boolean>(
    Taro.getStorageSync('agreeProto')
  );
  const [showPopup, setShowPopup] = useState<boolean>(false);
  const [mobile, setMobile] = useState(''); //手机号
  const [loadingText, setLoadingText] = useState('');
  const client_id: any = Taro.getStorageSync('client_id');
  const client_secret: any = Taro.getStorageSync('client_secret');

  useDidShow(async () => {
    Taro.onNetworkStatusChange(getNetWorkStatus);
    // // 1. 获取临时登录凭证 code
    // const loginRes = await Taro.login();
    // if (!loginRes.code) {
    //   Taro.showToast({
    //     title: '登录失败',
    //     icon: 'success',
    //   });
    //   return;
    // }
  });
  // 处理输入
  const handleInput = (e, name) => {
    const value = e.detail.value;

    // 只允许输入数字
    if (/^\d*$/.test(value) && name === 'captcha') {
      setCaptcha(value);
    } else if (/^\d*$/.test(value)) {
      setMobile(value);
    }
  };
  // 倒计时效果
  useEffect(() => {
    if (countdown > 0) {
      timerRef.current = setTimeout(() => {
        setCountdown(countdown - 1);
      }, 1000);
    }
    if (countdown === 0) {
      setIsSending(false);
    }
    return () => {
      if (timerRef.current) {
        clearTimeout(timerRef.current);
      }
    };
  }, [countdown]);
  // 发送验证码功能
  const sendCaptcha = async () => {
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    Taro.setStorageSync('mobile', mobile);
    if (!mobile) {
      showToast('请输入手机号码', 'error', 2);
      return;
    }
    //如果手机号不是11位，提示请输入正确手机号
    if (mobile.length !== 11) {
      showToast('请输入正确手机号码', 'error', 2);
      return;
    }

    if (isSending || countdown > 0) return;
    setIsSending(true);
    // 1.发送短信验证码,短信验证码登录是注册兼登录，及未注册会直接注册登录，已注册的就是登录
    //scenario:传registration表示注册 或 传login表示登录 或者 传getback表示找回密码，传logout表示注销
    sendCodeFun({
      phone_number: mobile,
      scenario: 'login',
    })
      .then((res) => {
        // 开始60秒倒计时
        setCountdown(60);
      })
      .catch((err) => {
        console.log(err, 'err======');
      });
  };

  // 更新后台接口
  const updateInfo = (avatarUrl: any, nickname: any) => {
    const userId = Taro.getStorageSync('userId');
    updateInfoFun({
      ucUserId: userId,
      ucLoginPhone: Taro.getStorageSync('mobile'),
      ucNickname: nickname
        ? nickname
        : Taro.getStorageSync(`nickname-${userId}`),
      ucAvatarUrl: avatarUrl,
      address: store.commonStore.province,
    }).then((res: any) => {
      //更新一次后不再需要更新，退出后需要再次更新
      store.commonStore.setNeedUpdateInfo(false);
    });
  };

  //更新用户信息
  const updateUserInfo = (avatarUrl: any, nickname: any, userId: string) => {
    let randomVal: any = '';
    if (
      Taro.getStorageSync(`nickname-${userId}`) === null &&
      nickname === null
    ) {
      randomVal = getRandomCombination(feature, identity, sence, '');

      Taro.setStorageSync(`nickname-${userId}`, randomVal);
    }
    Taro.setStorageSync(`avatarUrl-${userId}`, avatarUrl);
    //1.更新U家nickname信息
    updateBasicInfoFun({
      access_token: store.commonStore.accessToken,
      userId: Taro.getStorageSync('userId'),
      nickname: nickname ? nickname : randomVal,
    })
      .then((res: any) => {
        //2.登录成功后，刷新后台用户信息
        updateInfo(avatarUrl, nickname ? nickname : randomVal);
      })
      .catch((e: any) => {
        updateInfo(avatarUrl, nickname ? nickname : randomVal);
      });
  };

  //查询个人信息
  const getUserInfo = () => {
    userInfoFun({
      access_token: store.commonStore.accessToken,
    })
      .then((res: any) => {
        //保存个人信息
        Taro.setStorageSync('mobile', res.mobile);
        Taro.setStorageSync('userId', res.userId);
        //用户昵称从[特征] + 人物身份/状态] + [氛围/动作/场景]随机组合，和重复
        //首页进入页面没有昵称的时候随机生成一个昵称
        console.log(res, 'res=========');
        updateUserInfo(res.avatarUrl, res.nickname, res.userId);
      })
      .catch((e: any) => {});
  };

  //登录
  const loginFun = () => {
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    try {
      if (!selected) {
        showToast('请阅读并勾选协议', 'error', 2);
        return;
      }
      if (!mobile) {
        showToast('请输入手机号码', 'error', 2);
        return;
      }
      if (mobile.length !== 11) {
        showToast('请输入正确手机号码', 'error', 2);
        return;
      }
      if (!captcha) {
        showToast('请输入验证码', 'error', 2);
        return;
      }
      setLoadingText('加载中...');
      oauthTokenFun({
        client_id: client_id,
        client_secret: client_secret,
        grant_type: 'password',
        connection: 'sms',
        username: mobile,
        password: captcha,
      })
        .then((res: any) => {
          //登录失败的各种提示处理
          if (res.error) {
            setLoadingText('');
            showToast(loginErrorInfo[res.error], 'error', 2);
            return;
          }
          //登录成功的处理
          Taro.setStorageSync('access_token_login', res.access_token); //访问所需的访问令牌
          Taro.setStorageSync('refresh_token_login', res.refresh_token); //刷新token，可调用刷新token接口刷新出新的access_token(默认有效期1年)
          store.commonStore.setAccessToken(res.access_token);
          store.commonStore.setNeedUpdateInfo(true);
          getUserInfo();
          const loginOut = Taro.getStorageSync('loginOut');
          if (loginOut === '1') {
            //跳转到首页
            Taro.switchTab({ url: '/pages/home/index' });
            store.commonStore.setActiveTab(0);
            setTimeout(() => {
              Taro.removeStorageSync('loginOut');
            }, 2000);
          } else {
            setTimeout(() => {
              safeBack(2);
              setLoadingText('');
            }, 1000);
          }
        })
        .catch((err: any) => {
          console.error(err, 'err======登录失败');
          setLoadingText('');
        });
      //调用获取token方法
    } catch (error) {
      setLoadingText('');
    }
    //如果勾选同意按钮，并且验证码正确，跳转到首页
    if (selected) {
    } else {
      setShowPopup(true);
    }
  };
  //跳转到隐私协议
  const gotoPrivacyProtectFun = () => {
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    Taro.navigateTo({ url: '/subPagesAuth/privacyPolicy/index' });
  };

  //拒绝按钮
  const refuseFun = () => {
    setShowPopup(false);
  };

  //同意按钮
  const agreeFun = () => {
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    Taro.setStorageSync('agreeProto', !selected);
    setSelected(!selected);
    Taro.switchTab({ url: '/pages/home/index' });
    setShowPopup(false);
  };

  //弹框内容
  const content = () => {
    return (
      <View className="privacy-protect-modal">
        <View className="privacy-protect-desc">
          在你使用服务之前，请仔细阅读
          <Text
            className="privacy-protect-guide"
            onClick={() => gotoPrivacyProtectFun()}
          >
            《酒联网小程序隐私保护指引》
          </Text>
          。当您点击同意并开始使用产品服务时，即表示你已理解并同意该条款内容，该条款将对您产生法律约束力。如您拒绝，将会限制一些功能的使用。
        </View>
        <View className="common-btn">
          <Button className="common-btn-refuse" onClick={() => refuseFun()}>
            拒绝
          </Button>
          <Button className="common-btn-agree" onClick={() => agreeFun()}>
            同意
          </Button>
        </View>
      </View>
    );
  };

  return (
    <View className="register custom-left">
      <TitleBar
        showLeftBack={true}
        customLeft={TitleBarLeft({ flag: true })}
        title="登录/注册"
      ></TitleBar>
      <View className="page-body">
        <Text className="register-title">快速登录/注册</Text>
        <View className="input-content">
          <Input
            type="number"
            className="input-mobile"
            maxlength={11}
            value={mobile}
            placeholder="手机号码"
            onInput={(e) => handleInput(e, 'moile')}
          />
          <View className="captcha-container">
            <Input
              className="captcha-input"
              type="number"
              value={captcha}
              onInput={(e) => handleInput(e, 'captcha')}
              placeholder="请输入验证码"
              maxlength={6}
            />
            {countdown > 0 ? (
              <View className="countdown">
                <Text className="countdown-text">{countdown}s</Text>
              </View>
            ) : (
              <Button
                className="send-btn"
                onClick={sendCaptcha}
                disabled={false}
              >
                {'获取验证码'}
              </Button>
            )}
          </View>
        </View>

        <View className="checkbox-wrap">
          <Image
            src={
              selected
                ? 'https://file.linkcook.cn/image/wineMiniProgram/login/checked.png'
                : 'https://file.linkcook.cn/image/wineMiniProgram/login/unchecked.png'
            }
            onClick={() => {
              setSelected(!selected);
            }}
            className="check-icon"
          />
          我已阅读并同意
          <text
            className="login-checkbox-link"
            onClick={() => {
              Taro.navigateTo({ url: '/subPagesAuth/userAgreement/index' });
            }}
          >
            《用户协议》
          </text>
          和
          <text
            className="login-checkbox-link"
            onClick={() =>
              Taro.navigateTo({ url: '/subPagesAuth/privacyPolicy/index' })
            }
          >
            《隐私政策》
          </text>
        </View>
      </View>
      <Button className="login-btn-dark" onClick={loginFun}>
        登录/注册
      </Button>
      <StatusToast />
      <CommonPopup
        visible={showPopup}
        onClose={() => {
          setShowPopup(false);
        }}
        className="loginPopupClass"
        full={false}
        title="用户隐私保护提示"
        closeBtn={false}
        content={content()}
      ></CommonPopup>
      <LoadingSpinner text={loadingText} />
    </View>
  );
};

export default Register;
